package com.rules.admin.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gillion.grule.client.utils.EntityUtils;
import com.rules.admin.utils.ResultUtils;


import com.rules.admin.entity.RuleUserRole;
import com.rules.admin.entity.SysUser;
import com.rules.admin.login.Md5Util;
import com.rules.admin.service.RuleUserRoleService;
import com.rules.admin.service.SysGroupUserRoleService;
import com.rules.admin.service.SysUserService;
import com.rules.admin.utils.Constant;
import com.rules.core.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping({"/user"})
public class SysUserController {
   private static final Logger log = LoggerFactory.getLogger(SysUserController.class);
   @Autowired
   private SysUserService sysUserService;
   @Autowired
   private RuleUserRoleService ruleUserRoleService;
   @Autowired
   private SysGroupUserRoleService sysGroupUserRoleService;
   @Autowired
   private RedisUtils redisUtils;

   @RequestMapping(
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public IPage<SysUser> queryPage(String username, IPage<SysUser> page) {
      return this.sysUserService.queryPage(username, page);
   }

   @RequestMapping(
      value = {"/userName"},
      method = {RequestMethod.GET}
   )
   @ResponseBody
   public List<SysUser> getByGroupId(long groupId) {
      return this.sysUserService.getByGroupId(groupId);
   }

   @RequestMapping(
      value = {"/login"},
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public Map<String, Object> login(HttpServletRequest request, @RequestBody String account) throws Exception {
      if (account.isEmpty()) {
         return ResultUtils.getFaildResultData(new String[]{"用户名不能为空"});
      } else {
         Map obj = (Map) EntityUtils.readObjectFromJSONString(account, Map.class);
         if (!obj.containsKey("username")) {
            return ResultUtils.getFaildResultData(new String[]{"用户名不能为空"});
         } else if (!obj.containsKey("password")) {
            return ResultUtils.getFaildResultData(new String[]{"密码不能为空"});
         } else if (!obj.containsKey("captcha")) {
            return ResultUtils.getFaildResultData(new String[]{"验证码不能为空"});
         } else {
            String username = obj.get("username").toString();
            String password = obj.get("password").toString();
            String captcha = obj.get("captcha").toString();
            String vcode = this.redisUtils.get("vcode");
            return captcha.equals(vcode) ? this.sysUserService.getByUser(username, password) : ResultUtils.getFaildResultData(new String[]{"验证码错误，请重新输入！"});
         }
      }
   }

   @RequestMapping({"/logout"})
   @ResponseBody
   public Map<String, Object> logout() {
      this.sysUserService.logout();
      return ResultUtils.getSuccessResultData();
   }

   @RequestMapping(
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public Map<String, Object> addUser(@RequestBody SysUser sysUser) throws Exception {
      this.sysUserService.insert(sysUser);
      RuleUserRole ruleUserRole = new RuleUserRole();
      ruleUserRole.setRoleId(Constant.PERMISSION_COMMON);
      ruleUserRole.setUserId(this.sysUserService.findByUserName(sysUser.getUsername()).getId());
      this.ruleUserRoleService.save(ruleUserRole);
      return ResultUtils.getSuccessResultData();
   }

   @RequestMapping(
      value = {"/{id}"},
      method = {RequestMethod.DELETE}
   )
   @ResponseBody
   public Map<String, Object> deleteUser(@PathVariable("id") Long id) {
      List<Long> ids = this.ruleUserRoleService.getAdminUserId();
      if (ids.contains(id)) {
         return ResultUtils.getFaildResultData(new String[]{"删除失败，超级管理员不能被删除！"});
      } else {
         this.sysUserService.removeById(id);
         this.sysGroupUserRoleService.deleteByUserId(id);
         return ResultUtils.getSuccessResultData();
      }
   }

   @RequestMapping(
      method = {RequestMethod.DELETE}
   )
   @ResponseBody
   public Map<String, Object> deleteUsers(Long[] ids) {
      List<Long> adminIds = this.ruleUserRoleService.getAdminUserId();

      for(int i = 0; i < ids.length; ++i) {
         if (adminIds.contains(ids[i])) {
            return ResultUtils.getFaildResultData(new String[]{"删除失败，含有超级管理员"});
         }
      }

      this.sysUserService.delete(ids);
      return ResultUtils.getSuccessResultData();
   }

   @RequestMapping(
      method = {RequestMethod.PUT}
   )
   @ResponseBody
   public Map<String, Object> updateUser(@RequestBody SysUser sysUser) throws Exception {
      String format = "\\w{2,15}[@][a-z0-9]{2,}[.]\\p{Lower}{2,}";
      if (!sysUser.getEmail().matches(format)) {
         return ResultUtils.getFaildResultData(new String[]{"邮箱不合法，请重新输入！"});
      } else if ("".equals(sysUser.getPassword())) {
         return ResultUtils.getFaildResultData(new String[]{"密码是必须的，请重新输入！"});
      } else {
         sysUser.setPassword(Md5Util.md5Encode(sysUser.getUsername(), sysUser.getPassword()));
         this.sysUserService.updateById(sysUser);
         return ResultUtils.getSuccessResultData();
      }
   }

   @RequestMapping(
      value = {"/account"},
      method = {RequestMethod.PUT}
   )
   @ResponseBody
   public Map<String, Object> updateAccount(@RequestBody Map<String, Object> user) throws Exception {
      return this.sysUserService.updateAccount(user);
   }
}
